package com.gopay.scheduler.service.fund.impl;

import com.gopay.common.constants.holiday.HolidayType;
import com.gopay.common.cps.dao.fund.FundFileDao;
import com.gopay.common.domain.cust.CustInfoExtendItem;
import com.gopay.common.domain.fund.FundGopayFileEntity;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.cps.holiday.HolidayRemoteService;
import com.gopay.scheduler.dao.CustExtendItemDao;
import com.gopay.scheduler.dao.FundFileTemplateDao;
import com.gopay.scheduler.service.fund.FundFileTemplateService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

@Service("fundFileTemplateService")
public class FundFileTemplateServiceImpl implements FundFileTemplateService{
	protected Logger logger = Logger.getLogger(getClass());
	@Resource(name = "fundFileDao")
    private FundFileDao fundFileDao;
	
	@Resource(name="custExtendItemDao")
	private CustExtendItemDao custExtendItemDao;

	@Resource(name = "holidayRemoteService")
	private HolidayRemoteService holidayRemoteService;
	@Resource(name = "fundFileTemplateDao")
	private FundFileTemplateDao fundFileTemplateDao;
	Logger log = Logger.getLogger(FundFileTemplateServiceImpl.class);
	@Override
	public void insertFundFileInfoTemplate() {
		log.info("开始向数据库FUND_GOPAY_FILE数据表中添加模板数据");
		Map<String,FundGopayFileEntity> fileList = addEntityInfoToList();
		Set<Entry<String,FundGopayFileEntity>> entrySet =fileList.entrySet();
		if(fileList.size() != 0){			
		    for(Entry<String,FundGopayFileEntity> entry :entrySet){
		        FundGopayFileEntity fgfe = entry.getValue();
		        int resultCount = fundFileTemplateDao.getFundFileInfoByFileName(fgfe.getFileName());
		        if(resultCount != 0 ){
		            continue;
		        }else{		            
		            fundFileDao.save(fgfe);
					log.info(fgfe.getFileName()+"=================生成完成");
		        }
		    }
		    log.info("向数据库FUND_GOPAY_FILE数据表中添加模板数据完成");
		}
	}
	/**
	 * @Description:向集合中添加文件模板信息
	 * @return 一个10个文件模板信息的集合
	 * @author PanShiChao
	 */
	private Map<String,FundGopayFileEntity> addEntityInfoToList(){
	    Map<String,FundGopayFileEntity> fileList = new HashMap<String,FundGopayFileEntity>();
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		String fileNameDate = format.format(date);
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("itemKey", "fundOrgNo");
		List<CustInfoExtendItem> fundOrgNoList = getFundOrdNoByItemKey(param);
		List<String> fileTypeList = addFileTypeToList();
		for(String fileType : fileTypeList){
			List<String> fileNameList = createFileNameByFileType(fileNameDate,fileType,fundOrgNoList);
			for(String fileName: fileNameList){
			    FundGopayFileEntity fgfe = new FundGopayFileEntity();
			    String keyId = UUID.randomUUID().toString().replace("-", "");
	            fgfe.setKeyId(keyId);
	            fgfe.setFileName(fileName);
	            fgfe.setCreatedTs(date);
	            if(fileName.contains("allocation")){
                    Calendar calendar = Calendar.getInstance();  //得到日历
					try {
						calendar.setTime(holidayRemoteService.getTaddN(date,1,HolidayType.FUND_COMPANY));
					} catch (GopayException e) {
						e.printStackTrace();
						log.error("基金模板任务.............获取日历异常  因此allocation清算日期设置为"+new Date());
						calendar.setTime(DateUtils.add(date, Calendar.DATE, 1));
					}
                    fgfe.setSettleTime(calendar.getTime());
                }else{
                    fgfe.setSettleTime(date);
                }
	            fgfe.setLastUpdTs(date);
	            fgfe.setTotalSum(0);
	            fgfe.setTotalAmount(new BigDecimal(0));
	            if((fileName.contains("redeem")  && !fileName.contains("difference") && !fileName.contains("check")) ||
						(fileName.contains("withdraw") && !fileName.contains("difference"))){
	                fgfe.setFileStatus("2");//如果是赎回分红退款文件，将文件的状态设置称为处理中
	            }else{
	                fgfe.setFileStatus("1");
	            }
				if(fileName.contains("redeem_check")){
					fgfe.setFileStatus("2");
					fgfe.setTotalSum(null);
					fgfe.setTotalAmount(null);
				}
	            String fundOrgNo = fileName.substring(0,fileName.indexOf("_"));
	            System.out.println(fundOrgNo);
	            if(!"gopay".equals(fundOrgNo)){	                
	                Map<String,Object> fundOrgNoMap = new HashMap<String,Object>();
	                fundOrgNoMap.put("itemValue", fundOrgNo);
	                CustInfoExtendItem cei =custExtendItemDao.findFundCustIdByItemValue(fundOrgNoMap);
	                fgfe.setCustId(cei.getCustId());
	            }else{
	                fgfe.setCustId("GFB0000001");
	            }
	            fileList.put(fgfe.getFileName(),fgfe);
			}
		}
		return fileList;
	}
	/**
     * @Description: 将基金业务流程中关联的10个文件类型添加到集合中 
     * @return 一个10个文件类型的集合
     * @author PanShiChao
     */
	private List<String> addFileTypeToList(){
		List<String> fileTypeList = new ArrayList<String>();
		try {
			if(!holidayRemoteService.isHoliday(new Date(), HolidayType.FUND_COMPANY)){
				fileTypeList.add("allocation");
				fileTypeList.add("cancel");
				fileTypeList.add("transfer");
				fileTypeList.add("allocation_check");
				fileTypeList.add("withdraw");
				fileTypeList.add("redeem");
				fileTypeList.add("redeem_result");
				fileTypeList.add("redeem_pay_check");
               /**项目名称 : 基金二期优化   创建日期 : 17/1/22 10:06  Author : baiyunpeng  基金节假日不生成绑卡,签约模板文件 start*/
				fileTypeList.add("sign");
				fileTypeList.add("bindcard");
				/**项目名称 : 基金二期优化   创建日期 : 17/1/22 10:06  Author : baiyunpeng  end*/
				fileTypeList.add("redeem_check");
            }
		} catch (GopayException e) {
			e.printStackTrace();
		}
		return fileTypeList;
	}
	
	/**
     * @Description: 查询基金公司的机构代码 
     * @return 机构代码的集合
     * @author PanShiChao
     */
	private List<CustInfoExtendItem> getFundOrdNoByItemKey(Map<String,Object> param){
	    return custExtendItemDao.findFundCompanyCodeByItemKey(param);
	}
	/**
     * @Description: 查询基金公司的机构代码
     * @param  fileNameDate:文件生成日期
     * @param  fileType：文件类型
     * @param  fundOrgNoList：机构代码集合 
     * @return 包含文件名称的集合
     * @author PanShiChao
     */
	private List<String> createFileNameByFileType(String fileNameDate,String fileType,List<CustInfoExtendItem> fundOrgNoList){
	    List<String> fundNameList = new ArrayList<String>();
		//获取文件名
		String fileDay = geneFileDay();
	    switch (fileType) {
        case "allocation":
            for(CustInfoExtendItem ciei:fundOrgNoList){
                String fundOrgNo = ciei.getItemValue();
                String fileName = fundOrgNo+"_"+fileType+"_"+fileNameDate;
                fundNameList.add(fileName);
            }
            break;
        case "redeem":
            for(CustInfoExtendItem ciei:fundOrgNoList){
                String fundOrgNo = ciei.getItemValue();
                String fileName = fundOrgNo+"_"+fileType+"_"+fileNameDate;
                fundNameList.add(fileName);
            }
            break;
        case "redeem_result":
            String [] strs = fileType.split("_");
            for(CustInfoExtendItem ciei:fundOrgNoList){
                String fundOrgNo = ciei.getItemValue();
                String fileName = fundOrgNo+"_"+strs[0]+"_"+fileNameDate+"_"+strs[1];
                fundNameList.add(fileName);
            }
            break;
        case "sign":
            for(CustInfoExtendItem ciei:fundOrgNoList){
                String fundOrgNo = ciei.getItemValue();
                String fileName = fundOrgNo+"_"+fileType+"_"+fileNameDate;
                fundNameList.add(fileName);
            }
            break;
        case "cancel":
            for(CustInfoExtendItem ciei:fundOrgNoList){
                String fundOrgNo = ciei.getItemValue();
                String fileName = fundOrgNo+"_"+fileType+"_"+(fileDay==null?fileNameDate:fileDay);
                fundNameList.add(fileName);
            }
            break;
        case "redeem_pay_check":
            for(CustInfoExtendItem ciei:fundOrgNoList){
                String fundOrgNo = ciei.getItemValue();
                String fileName = fundOrgNo+"_"+fileType+"_"+fileNameDate;
                fundNameList.add(fileName);
            }
            break;
		case "redeem_check":
			for(CustInfoExtendItem ciei:fundOrgNoList){
				String fundOrgNo = ciei.getItemValue();
				String fileName = fundOrgNo+"_"+fileType+"_"+fileNameDate;
				fundNameList.add(fileName);
			}
        case "allocation_check":
            for(CustInfoExtendItem ciei:fundOrgNoList){
                String fundOrgNo = ciei.getItemValue();
                String fileName = fundOrgNo+"_"+fileType+"_"+fileNameDate;
                fundNameList.add(fileName);
            }
            break;
        case "transfer":
            String fileName = "gopay_"+fileType+"_"+fileNameDate;
            fundNameList.add(fileName);
            break;
        case "withdraw":
            String fileWithdrawName = "gopay_"+fileType+"_"+fileNameDate;
            fundNameList.add(fileWithdrawName);
            break;
        case "bindcard":
            String fileBindCardName = "gopay_"+fileType+"_"+fileNameDate;
            fundNameList.add(fileBindCardName);
            break;
        default:
            fileName = null;
            break;
        }
	    
	    return fundNameList;
	}

	private String geneFileDay() {
		try {
			Calendar date = Calendar.getInstance();
			date.setTime(new Date());
			for (int i = 1; i < 20; i++) {
				Date fileDay = null;
				date.set(Calendar.DATE, date.get(Calendar.DATE) - 1);
				fileDay = date.getTime();
				if(!holidayRemoteService.isHoliday(fileDay, HolidayType.FUND_COMPANY)){
					return DateUtils.formatDate(date.getTime(), "yyyyMMdd");
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}
}
